#
#===============================================================================
#
#         FILE:  QDB.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/20/2010 06:06:11 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::QDB;

use XML::RSS;
use LWP::UserAgent;
use HTML::Entities;

sub register {
    my $self = shift;

    return ('cmd' => 'qdb', 'pat' => '^!qdb\s*(.*)');
}

sub help {
    my $self = shift;
    
    return ('Use no arguments to get random quote, or specify a specific ID to display from the quote database');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    $msgtxt =~ /^!qdb\s*(.*)/;
    
    my $arg = $1;
    if( $arg && $arg !~ /^[0-9]+$/ ) {
	$arg = undef;
    }

    my $url = 'http://qdb.us/qdb.xml?fixed=0&client=googpl&action=';
    if( $arg ) {
	$url .= 'quote&quote='.$arg;
    }
    else {
	$url .= 'random';
    }

    my $ua = LWP::UserAgent->new;
    my $resp = $ua->get($url);
    if( ! $resp->is_success ) {
	return;
    }

    my $rss = XML::RSS->new;
    if( ! $rss->parse($resp->decoded_content) ) {
	return;
    }

    if( ! ref($rss->{'items'}) eq 'ARRAY' ) {
	return;
    }
    my $desc = $rss->{'items'}[0]{'description'};
    $desc =~ s/<[^>]*>//mg;
    $desc =~ s/&nbsp;/ /mg;

    if( ! $arg ) {
	$kernel->post($sender => privmsg => $target => $rss->{'items'}[0]{'link'});
    }

    foreach my $l (split /\n/, $desc) {
        $kernel->post($sender => privmsg => $target => decode_entities($l));
    }
}

1;
